package io.xccit.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.xccit.model.system.SysRoleMenu;
import io.xccit.model.vo.AssginMenuVo;
import io.xccit.system.mapper.ISysRoleMenuMapper;
import io.xccit.system.service.ISysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author CH_ywx
 * @date 2023-06-26
 * @description
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<ISysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Resource
    private ISysRoleMenuMapper sysRoleMenuMapper;
    @Override
    public List<SysRoleMenu> selectMenuByRoleID(Long roleID) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId,roleID);
        return sysRoleMenuMapper.selectList(wrapper);
    }

    @Override
    public boolean doAssgin(AssginMenuVo assginMenuVo) {
        List<Long> menuIdList = assginMenuVo.getMenuIdList();
        Long roleId = assginMenuVo.getRoleId();
        //删除旧的
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));
        if (CollectionUtils.isEmpty(sysRoleMenus)){
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setId(1L);
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(1L);
            sysRoleMenus = new ArrayList<>();
            sysRoleMenus.add(sysRoleMenu);
        }
        List<Long> hadRoleMenuIds = sysRoleMenus.stream().map(SysRoleMenu::getId).collect(Collectors.toList());
        sysRoleMenuMapper.deleteBatchIds(hadRoleMenuIds);
        //添加新的
        for (Long menuID : menuIdList) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuID);
            sysRoleMenuMapper.insert(sysRoleMenu);
        }
        return true;
    }
}
